<template>
    <el-form 
        ref="formRef"
        :model="settingForm"
        :rules="rules"
        label-width="120px"
        class="setting-form"
        v-loading="loading"
    >
        <el-form-item label="房间名称" prop="RoomName">
            <el-input 
                v-model="settingForm.roomName" 
                placeholder="请输入房间名称"
                maxlength="50"
                show-word-limit
            />
        </el-form-item>

        <el-form-item label="房间封面" prop="RoomPhoto">
            <div class="cover-uploader">
                <div 
                    class="upload-trigger"
                    @click="showFileDialog = true"
                >
                    <el-image
                        v-if="settingForm.roomPhoto"
                        :src="settingForm.roomPhoto"
                        class="cover-preview"
                        fit="cover"
                    />
                    <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
                </div>
                <div class="upload-tip">图片建议尺寸：1920x1080，支持jpg、png格式</div>
            </div>
        </el-form-item>

        <el-form-item label="房间简介" prop="RoomInformation">
            <el-input
                v-model="settingForm.roomInformation"
                type="textarea"
                :rows="4"
                placeholder="请输入房间简介"
                maxlength="200"
                show-word-limit
            />
        </el-form-item>

        <el-form-item label="房间标签" prop="RoomTags">
            <el-select
                v-model="selectedTags"
                multiple
                filterable
                allow-create
                default-first-option
                :reserve-keyword="false"
                placeholder="请选择或输入标签"
                @change="handleTagsChange"
            >
                <el-option
                    v-for="tag in tagOptions"
                    :key="tag"
                    :label="tag"
                    :value="tag"
                />
            </el-select>
        </el-form-item>

        <el-form-item label="推流地址" prop="RoomAddress">
            <el-input
                v-model="settingForm.roomAddress"
                placeholder="请输入推流地址"
                disabled
            >
                <template #append>
                    <el-button @click="copyAddress">
                        <el-icon><DocumentCopy /></el-icon>
                        复制
                    </el-button>
                </template>
            </el-input>
        </el-form-item>
    </el-form>

    <file-dialog
        v-model="showFileDialog"
        :multiple="false"
        @select="handleFileSelect"
        :suffixes="['jpg', 'png']"
    />
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { Plus, DocumentCopy } from '@element-plus/icons-vue'
import { CreateSetting, getSetting, updateSetting, type LiveSetting } from '@/apis/live'
import FileDialog from '@/components/FileDialog/index.vue'

const emit = defineEmits(['update'])

const formRef = ref<FormInstance>()
const loading = ref(false)
const showFileDialog = ref(false)

// 标签选项
const tagOptions = ref(['游戏', '娱乐', '音乐', '知识', '体育'])
const selectedTags = ref<string[]>([])
const settingForm = ref<LiveSetting>({
    roomName: '',
    roomPhoto: '',
    roomInformation: '',
    roomTags: '',
    roomAddress: '',
    roomStatus: 1,
    status: 1,
    uuid: '',
    roomMessagesGroupsId: 0,
    userUuid: ''
})

const rules = {
    RoomName: [
        { required: true, message: '请输入房间名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    RoomPhoto: [
        { required: true, message: '请上传房间封面', trigger: 'change' }
    ],
    RoomInformation: [
        { required: true, message: '请输入房间简介', trigger: 'blur' },
        { max: 200, message: '长度不能超过 200 个字符', trigger: 'blur' }
    ],
    RoomTags: [
        { required: true, message: '请选择房间标签', trigger: 'change' }
    ]
}

// 获取设置
const fetchSetting = async () => {
    loading.value = true
    try {
        return
        // const data = await getSetting()
        // Object.assign(settingForm.value, data)
        // // 解析标签字符串为��组
        // if (data.roomTags) {
        //     selectedTags.value = data.roomTags.split(',')
        // }
    } catch (error) {
        console.error('获取设置失败:', error)
        ElMessage.error('获取设置失败')
    } finally {
        loading.value = false
    }
}

// 处理文件选择
const handleFileSelect = (files: any[]) => {
    if (files && files.length > 0) {
        settingForm.value.roomPhoto = files[0].path
    }
}

// 处理标签变化
const handleTagsChange = (tags: string[]) => {
    settingForm.value.roomTags = tags.join(',')
}

// 复制推流地址
const copyAddress = () => {
    if (!settingForm.value.roomAddress) {
        ElMessage.warning('推流地址为空')
        return
    }
    
    navigator.clipboard.writeText(settingForm.value.roomAddress)
        .then(() => {
            ElMessage.success('复制成功')
        })
        .catch(() => {
            ElMessage.error('复制失败')
        })
}

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return
    
    const valid = await formRef.value.validate()
    if (!valid) return
debugger
    loading.value = true
    try {
        await CreateSetting(settingForm.value)
        ElMessage.success('保存成功')
        emit('update', settingForm.value)
        return true
    } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败')
        return false
    } finally {
        loading.value = false
    }
}

// 暴露方法给父组件
defineExpose({
    handleSubmit,
    formRef
})

onMounted(() => {
    fetchSetting()
})
</script>

<style scoped lang="scss">
.setting-form {
    .cover-uploader {
        .upload-trigger {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
            width: 240px;
            height: 135px;
            display: flex;
            align-items: center;
            justify-content: center;
            
            &:hover {
                border-color: var(--el-color-primary);
            }
        }
        
        .cover-uploader-icon {
            font-size: 28px;
            color: #8c939d;
        }
        
        .cover-preview {
            width: 100%;
            height: 100%;
            display: block;
        }
        
        .upload-tip {
            font-size: 12px;
            color: var(--el-text-color-secondary);
            margin-top: 8px;
        }
    }
}
</style> 